﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Mrc.AuthCenter.Models;
using Surging.Core.ProxyGenerator;
using Mrc.AuthService;
using Mrc.AuthService.IService;
using Mrc.Entities;
namespace Mrc.AuthCenter.Controllers
{
    public class HomeController : Controller
    {
        private readonly IServiceProxyFactory _serviceProxyFactory;
        private readonly IAccountLogonService  _accountLogonService;
        public HomeController(IServiceProxyFactory serviceProxyFactory)
        {
            _serviceProxyFactory = serviceProxyFactory;
            _accountLogonService = _serviceProxyFactory.CreateProxy<IAccountLogonService>("AccountLogon");
        }
        public IActionResult Index()
        {         
            return View();
        }
        public async Task<ActionResult> Login()
        {
            return await Task.Run(() => View());
        }
        public async Task<JsonResult> LoginPost(string userName,string password)
        {
            return await Task.Run(async() => {
                AjaxResult result=AjaxResult.CreateResult<string>(ResultStatus.Failed,"");
                var data = await _accountLogonService.CheckLogon(userName,password);
                if(data==null)
                {
                    result.msg = "登录失败";
                }
                else
                {
                    Dictionary<string, object> payLoad = new Dictionary<string, object>();
                    payLoad.Add("sub", "user");
                    payLoad.Add("jti",Guid.NewGuid().ToString());
                    payLoad.Add("nbf", null);
                    payLoad.Add("exp", null);
                    payLoad.Add("iss", "Issuser");
                    payLoad.Add("aud", "user");
                    payLoad.Add("user", data.Name);
                    payLoad.Add("isLock", data.State);
                    var token= TokenManager.CreateToken(payLoad,30);
                    result=AjaxResult.CreateResult<string>(ResultStatus.OK, "登录成功", token);
                    HttpContext.Response.Cookies.Append("MRCTOKEN", token, new Microsoft.AspNetCore.Http.CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(30)
                    });
                }
                return Json(result);
            });
        }

        [Login]
        public async Task<JsonResult> Privacy()
        {
            var result = await _accountLogonService.CheckLogon("admin", "111111");
            return Json(result);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
